# Based on EVA, BEIT, timm and DeiT code bases
# https://github.com/baaivision/EVA
# https://github.com/rwightman/pytorch-image-models/tree/master/timm
# https://github.com/microsoft/unilm/tree/master/beit
# https://github.com/facebookresearch/deit/
# https://github.com/facebookresearch/dino
# --------------------------------------------------------'
import math
from functools import partial
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from timm.models.layers import drop_path, to_2tuple, trunc_normal_
from timm.models.registry import register_model
from timechat.common.utils import is_url
from timechat.common.dist_utils import download_cached_file

#定义模型的默认配置参数
def _cfg(url='', **kwargs):
    return {
        'url': url, #模型权重的下载链接
        'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None,
        'crop_pct': .9, 'interpolation': 'bicubic',
        'mean': (0.5, 0.5, 0.5), 'std': (0.5, 0.5, 0.5),
        **kwargs
    }

#实现Stochastic Depth（随机深度），在训练时随机丢弃一些残差分支
class DropPath(nn.Module):
    """Drop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks).
    """
    def __init__(self, drop_prob=None):
        super(DropPath, self).__init__()
        self.drop_prob = drop_prob #丢弃概率

    def forward(self, x):
        return drop_path(x, self.drop_prob, self.training) #根据drop_prob和训练模型决定是否丢弃

    def extra_repr(self) -> str:
        return 'p={}'.format(self.drop_prob) #返回字符串表示，显示丢弃概率

#实现多层感知机
class Mlp(nn.Module):
    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        self.fc1 = nn.Linear(in_features, hidden_features) #线性变换
        self.act = act_layer() #激活函数层
        self.fc2 = nn.Linear(hidden_features, out_features) #线性变化
        self.drop = nn.Dropout(drop) #丢弃层

    def forward(self, x):
        x = self.fc1(x) #将输入映射到隐藏层
        x = self.act(x) #应用激活函数
        # x = self.drop(x)
        # commit this for the orignal BERT implement 
        x = self.fc2(x) #将隐藏层映射到输出层
        x = self.drop(x) #丢弃，防止过拟合
        return x

#实现多头注意力机制，支持相对位置偏置
class Attention(nn.Module):
    def __init__(
            self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
            proj_drop=0., window_size=None, attn_head_dim=None):
        super().__init__()
        self.num_heads = num_heads
        head_dim = dim // num_heads
        if attn_head_dim is not None:
            head_dim = attn_head_dim
        all_head_dim = head_dim * self.num_heads #计算所有注意力头的总维度
        self.scale = qk_scale or head_dim ** -0.5 #缩放因子

        self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False) #创建一个线性层，将输入映射到q，k，v空间
        if qkv_bias:
            self.q_bias = nn.Parameter(torch.zeros(all_head_dim)) #如果有偏置项，则置为0
            self.v_bias = nn.Parameter(torch.zeros(all_head_dim)) #同上
        else:
            self.q_bias = None
            self.v_bias = None

        if window_size:
            self.window_size = window_size
            self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 #计算相对位置偏置的总数量
            #初始化相对位置偏置表
            self.relative_position_bias_table = nn.Parameter(
                torch.zeros(self.num_relative_distance, num_heads))  # 2*Wh-1 * 2*Ww-1, nH
            # cls to token & token 2 cls & cls to cls

            # get pair-wise relative position index for each token inside the window
            coords_h = torch.arange(window_size[0])
            coords_w = torch.arange(window_size[1])
            coords = torch.stack(torch.meshgrid([coords_h, coords_w]))  #生成窗口内的坐标网格，形状为 (2, window_size[0], window_size[1])
            coords_flatten = torch.flatten(coords, 1)  #将坐标网格展平为 (2, window_size[0] * window_size[1])
            relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]  #计算所有令牌对之间的相对坐标差
            relative_coords = relative_coords.permute(1, 2, 0).contiguous()  #调整维度顺序为 (Wh*Ww, Wh*Ww, 2)
            relative_coords[:, :, 0] += window_size[0] - 1
            relative_coords[:, :, 1] += window_size[1] - 1
            relative_coords[:, :, 0] *= 2 * window_size[1] - 1 #将相对坐标偏移为非负值，便于索引
            relative_position_index = \
                torch.zeros(size=(window_size[0] * window_size[1] + 1, ) * 2, dtype=relative_coords.dtype) #初始化相对位置索引表
            relative_position_index[1:, 1:] = relative_coords.sum(-1)  #填充窗口内令牌对的相对位置索引
            relative_position_index[0, 0:] = self.num_relative_distance - 3
            relative_position_index[0:, 0] = self.num_relative_distance - 2
            relative_position_index[0, 0] = self.num_relative_distance - 1

            self.register_buffer("relative_position_index", relative_position_index) #将相对位置索引注册为缓冲区
        else:
            self.window_size = None
            self.relative_position_bias_table = None
            self.relative_position_index = None

        self.attn_drop = nn.Dropout(attn_drop) #初始化注意力权重的 Dropout 层
        self.proj = nn.Linear(all_head_dim, dim) #初始化投影层，将多头注意力的输出映射回原始维度
        self.proj_drop = nn.Dropout(proj_drop) #初始化投影后的 Dropout 层

    def forward(self, x, rel_pos_bias=None):
        B, N, C = x.shape #批次大小，序列长度，特征维度
        qkv_bias = None
        if self.q_bias is not None:
            qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias)) #如果启用了偏置项，则将 Query、Key 和 Value 的偏置拼接为一个向量
        # qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
        qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) #线性变换生成q，k，v
        qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) #重塑张量，调整维度顺序
        q, k, v = qkv[0], qkv[1], qkv[2]   #拆分q，k，v

        q = q * self.scale #对q应用缩放因子
        attn = (q @ k.transpose(-2, -1)) #计算q和k的点积，得到注意力权重矩阵

        if self.relative_position_bias_table is not None:
            relative_position_bias = \
                self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
                    self.window_size[0] * self.window_size[1] + 1,
                    self.window_size[0] * self.window_size[1] + 1, -1)  # Wh*Ww,Wh*Ww,nH
            relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()  # nH, Wh*Ww, Wh*Ww
            attn = attn + relative_position_bias.unsqueeze(0) #如果启用了相对位置偏置，则将其加到注意力权重上

        if rel_pos_bias is not None:
            attn = attn + rel_pos_bias #如果提供了外部位置偏置，则将其加到注意力权重上

        attn = attn.softmax(dim=-1) #对注意力权重应用softmax得到概率分布
        attn = self.attn_drop(attn) #应用dropout

        x = (attn @ v).transpose(1, 2).reshape(B, N, -1) #对v应用加权求和，调整顺序并重塑为（B,N,C）
        x = self.proj(x) #进行线性投影
        x = self.proj_drop(x) #对投影后的输出应用dropout
        return x


class Block(nn.Module):

    def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
                 drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm,
                 window_size=None, attn_head_dim=None):
        super().__init__()
        self.norm1 = norm_layer(dim) #创建第一个归一化层
        self.attn = Attention(
            dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
            attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim) #实例化一个注意力机制模块
        # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() #使用droppath
        self.norm2 = norm_layer(dim) #创建第二个归一化层，对前馈网络的输入进行归一化
        mlp_hidden_dim = int(dim * mlp_ratio) #计算前馈网络的隐藏层维度
        self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) #实例化一个多层感知机，对归一化后的特征进行非线性变换

        if init_values is not None and init_values > 0: #判断是否需要初始化可学习的缩放参数
            self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) #可学习参数，用于缩放注意力机制的输出
            self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) #可学习参数，用于缩放前馈网络的输出
        else:
            self.gamma_1, self.gamma_2 = None, None

    def forward(self, x, rel_pos_bias=None):
        if self.gamma_1 is None: #不使用
            x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias)) #对输入x进行归一化后输入注意力机制模块，将输出通过drop_path后与输入相加，实现残差连接
            x = x + self.drop_path(self.mlp(self.norm2(x))) #对输入x进行归一化后输入前馈神经网络，将输出通过drop_path后与输入相加，实现残差连接
        else: #使用
            x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias)) #对注意力机制的输出乘以gamma_1进行缩放
            x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) #对前馈神经网络的输出乘以gamma_2进行缩放
        return x

#用于将图像划分为多个小块并进行嵌入
class PatchEmbed(nn.Module):
    """ Image to Patch Embedding
    """
    def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
        super().__init__()
        img_size = to_2tuple(img_size) #将图像大小转换为元组形式，确保是二维的
        patch_size = to_2tuple(patch_size) #同理，将小块大小转换为元组形式
        num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) #计算图像可以划分成的小块
        self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) #存储小块的形状信息
        self.img_size = img_size
        self.patch_size = patch_size
        self.num_patches = num_patches

        self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) #定义一个二维卷积层，用于将图像划分成为小块并映射到嵌入空间

    def forward(self, x, **kwargs):
        B, C, H, W = x.shape #批次大小，通道数，高度，宽度
        # FIXME look at relaxing size constraints
        assert H == self.img_size[0] and W == self.img_size[1], \
            f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." #断言输入图像大小和模型期望的大小一致，否则报错
        x = self.proj(x).flatten(2).transpose(1, 2) #利用卷积层将图像划分为小块并进行嵌入，然后将结果展平并转置
        return x

#用于计算相对位置偏置，帮助注意力机制更好地捕捉位置信息
class RelativePositionBias(nn.Module):

    def __init__(self, window_size, num_heads):
        super().__init__()
        self.window_size = window_size
        self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 #计算相对距离的数量
        self.relative_position_bias_table = nn.Parameter(
            torch.zeros(self.num_relative_distance, num_heads)) #定义一个可学习的相对位置偏置表，初始化全0
        # cls to token & token 2 cls & cls to cls

        # get pair-wise relative position index for each token inside the window
        coords_h = torch.arange(window_size[0]) #生成从0到窗口高度-1的坐标序列
        coords_w = torch.arange(window_size[1]) #生成从0到窗口宽度-1的坐标序列
        coords = torch.stack(torch.meshgrid([coords_h, coords_w])) #将高度和宽度坐标组合成一个二维网格坐标
        coords_flatten = torch.flatten(coords, 1)  #将坐标张量展平
        relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]  #计算所有位置对之间的相对坐标
        relative_coords = relative_coords.permute(1, 2, 0).contiguous()  #对相对坐标进行转置和内存布局调整
        relative_coords[:, :, 0] += window_size[0] - 1 #将相对坐标的高度部分偏移，使其从 0 开始
        relative_coords[:, :, 1] += window_size[1] - 1 #将相对坐标的宽度部分偏移，使其从 0 开始
        relative_coords[:, :, 0] *= 2 * window_size[1] - 1 #将高度相对坐标进行缩放，以便与宽度相对坐标结合成一维索引
        relative_position_index = \
            torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype) #创建一个相对位置索引张量，存储每个位置对的索引
        relative_position_index[1:, 1:] = relative_coords.sum(-1) #填充相对位置索引张量中窗口内token之间的部分
        relative_position_index[0, 0:] = self.num_relative_distance - 3 #设置[cls]到其他token的相对位置索引
        relative_position_index[0:, 0] = self.num_relative_distance - 2 #设置其他token到[cls]的相对位置索引
        relative_position_index[0, 0] = self.num_relative_distance - 1 #设置[cls]到自身的相对位置索引

        self.register_buffer("relative_position_index", relative_position_index) #将相对位置索引注册为一个缓冲区，这样它就会被保存在模型中，不会被当做可训练参数

        # trunc_normal_(self.relative_position_bias_table, std=.02)

    def forward(self):
        relative_position_bias = \
            self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
                self.window_size[0] * self.window_size[1] + 1,
                self.window_size[0] * self.window_size[1] + 1, -1) #根据相对位置索引从相对位置偏置表中获取对应的偏置值，并调整形状
        return relative_position_bias.permute(2, 0, 1).contiguous() #对偏置张量进行转置和内存布局调整，使其形状符合注意力机制的期望，最后返回相对位置偏置


class VisionTransformer(nn.Module):
    """ Vision Transformer with support for patch or hybrid CNN input stage
    """
    def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
                 num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
                 drop_path_rate=0., norm_layer=nn.LayerNorm, init_values=None,
                 use_abs_pos_emb=True, use_rel_pos_bias=False, use_shared_rel_pos_bias=False,
                 use_mean_pooling=True, init_scale=0.001, use_checkpoint=False):
        super().__init__()
        self.image_size = img_size
        self.num_classes = num_classes
        self.num_features = self.embed_dim = embed_dim  # num_features for consistency with other models

        self.patch_embed = PatchEmbed(
            img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) #将图像划分为patch，并做线性投影（卷积）
        num_patches = self.patch_embed.num_patches #计算总的patch数量

        self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) #引入一个可训练的class token，用于分类
        if use_abs_pos_emb:
            self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) #如果使用绝对位置编码，初始化一个可学习的pos_embed向量
        else:
            self.pos_embed = None
        self.pos_drop = nn.Dropout(p=drop_rate) #位置编码后，添加dropout防止过拟合

        if use_shared_rel_pos_bias:
            self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads) #若使用共享的相对位置偏置
        else:
            self.rel_pos_bias = None
        self.use_checkpoint = use_checkpoint #是否使用检查点保存内存

        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]  #生成一个列表dpr，包含从0到drop_path_rate线性变化的值，用于每一层的drop path概率
        self.use_rel_pos_bias = use_rel_pos_bias
        self.blocks = nn.ModuleList([
            Block(
                dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
                drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
                init_values=init_values, window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None)
            for i in range(depth)]) #构造多个block，每层可选使用相对位置偏置，残差缩放等功能
#         self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim)
#         self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None
#         self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()

        if self.pos_embed is not None:
            trunc_normal_(self.pos_embed, std=.02) #如果使用位置嵌入，则使用trunc_normal_函数进行初始化，标准差为0.02
        trunc_normal_(self.cls_token, std=.02) #使用trunc_normal_对cls_token进行初始化，标准差为0.02
        # trunc_normal_(self.mask_token, std=.02)
#         if isinstance(self.head, nn.Linear):
#             trunc_normal_(self.head.weight, std=.02)
        self.apply(self._init_weights) #对模型中的所有模块应用_init_weights函数，进行权重初始化
        self.fix_init_weight() #对模型中的权重进行调整，以改善训练稳定性
#         if isinstance(self.head, nn.Linear):
#             self.head.weight.data.mul_(init_scale)
#             self.head.bias.data.mul_(init_scale)

    def fix_init_weight(self):
        def rescale(param, layer_id):
            param.div_(math.sqrt(2.0 * layer_id)) #将参数param除以sqrt(2.0 * layer_id)，从而对权重进行缩放

        for layer_id, layer in enumerate(self.blocks): #遍历每个block层，获得其索引layer_id
            rescale(layer.attn.proj.weight.data, layer_id + 1) #对当前block层的注意力机制中的投影权重进行缩放，layer_id + 1为缩放因子
            rescale(layer.mlp.fc2.weight.data, layer_id + 1) #对当前block层的多层感知机中的第二个全连接层权重进行缩放，layer_id + 1为缩放因子

    def _init_weights(self, m):
        if isinstance(m, nn.Linear): #检查当前模块m是否为nn.Liner类型
            trunc_normal_(m.weight, std=.02) #如果是，则使用截断正态分布对权重m.weight进行初始化，标准差为0.02
            if isinstance(m, nn.Linear) and m.bias is not None: #如果当前是nn.Liner类型且有偏置
                nn.init.constant_(m.bias, 0) #将偏置初始化为0
        elif isinstance(m, nn.LayerNorm): #当前模块如果是nn.LayerNorm类型
            nn.init.constant_(m.bias, 0) #将偏置初始化为0
            nn.init.constant_(m.weight, 1.0) #将权重初始化为1.0

    def get_classifier(self):
        return self.head #返回模型的最后一层self.head，该层用于将特征映射到类别，是模型的分类器部分

    def reset_classifier(self, num_classes, global_pool=''):
        self.num_classes = num_classes #更新模型的类别数
        self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() #根据新的类别数重新定义分类器层head：如果大于0，则使用线性层将嵌入维度映射到类别数，反之不进行任何操作

    def forward_features(self, x):
        x = self.patch_embed(x) #将输入图像x划分为多个patch，并映射到嵌入空间
        batch_size, seq_len, _ = x.size() #获取当前批次的大小，序列长度

        cls_tokens = self.cls_token.expand(batch_size, -1, -1) #将cls_token扩展到与当前批次大小一致的形状(batch_size,1,embed_dim)
        x = torch.cat((cls_tokens, x), dim=1) #将cls_token拼接到patch嵌入序列的前面，形成新的序列(batch_size,seq_len+1,embed_dim)
        if self.pos_embed is not None:
            x = x + self.pos_embed #如果使用了绝对位置嵌入，则将位置嵌入加到当前序列x上
        x = self.pos_drop(x) #对嵌入后的x应用dropout

        rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None #如果使用相对位置偏置，则计算相对位置偏置，反正设为None
        for blk in self.blocks: #遍历每个block层
            if self.use_checkpoint: #如果使用了检查点
                x = checkpoint.checkpoint(blk, x, rel_pos_bias) #使用checkpoint.checkpoint方法来执行前向传播，这会在不保存中间梯度的情况下计算输出，从而节省内存
            else:
                x = blk(x, rel_pos_bias) #如果不使用检查点，将当前序列x和相对位置偏置传给block进行前向传播
        return x #返回经过所有block层处理后的特征序列x
#         x = self.norm(x)

#         if self.fc_norm is not None:
#             t = x[:, 1:, :]
#             return self.fc_norm(t.mean(1))
#         else:
#             return x[:, 0]

    def forward(self, x):
        x = self.forward_features(x) #提取输入图像特征x
#         x = self.head(x)
        return x

    def get_intermediate_layers(self, x):
        x = self.patch_embed(x) #将输入图像x划分为多个patch，并映射到嵌入空间
        batch_size, seq_len, _ = x.size() #获取当前批次的大小，序列长度

        cls_tokens = self.cls_token.expand(batch_size, -1, -1)  #将cls_token扩展到与当前批次大小一致的形状(batch_size,1,embed_dim)
        x = torch.cat((cls_tokens, x), dim=1) #将cls_token拼接到patch嵌入序列的前面，形成新的序列(batch_size,seq_len+1,embed_dim)
        if self.pos_embed is not None:
            x = x + self.pos_embed #如果使用了绝对位置嵌入，则将位置嵌入加到当前序列x上
        x = self.pos_drop(x) #对嵌入后的x应用dropout

        features = [] #用于存储每层的输出
        rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None #如果使用相对位置偏置，则计算相对位置偏置，反正设为None
        for blk in self.blocks: #遍历每个block层
            x = blk(x, rel_pos_bias) #将当前序列x和相对位置偏置传给block进行前向传播
            features.append(x) #将当前层的输出x添加到列表中

        return features


def interpolate_pos_embed(model, checkpoint_model):
    if 'pos_embed' in checkpoint_model: #检查预训练模型的权重中是否包含嵌入键'pos_embed'
        pos_embed_checkpoint = checkpoint_model['pos_embed'].float() #获取嵌入位置张量，并将其转换为浮点类型
        embedding_size = pos_embed_checkpoint.shape[-1] #获取嵌入位置的维度大小
        num_patches = model.patch_embed.num_patches #获取当前模型划分的patch数量
        num_extra_tokens = model.pos_embed.shape[-2] - num_patches #计算位置嵌入中额外的token数量
        # height (== width) for the checkpoint position embedding
        orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) #计算预训练位置嵌入对应的宽高
        # height (== width) for the new position embedding
        new_size = int(num_patches ** 0.5) #计算当前位置嵌入的宽高
        # class_token and dist_token are kept unchanged
        if orig_size != new_size: #如果预训练位置嵌入的大小与当前模型所需大小不同
            print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) #打印插值信息
            extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] #提取位置嵌入中额外的token部分
            # only the position tokens are interpolated
            pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] #提取位置嵌入中的patch位置token部分
            pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) #将patch位置token调整为（batch_size,embedding_size,orig_size,orig_size）
            pos_tokens = torch.nn.functional.interpolate(
                pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) #使用双三次插值将位置token的大小调整为(new_size,new_size)
            pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) #将插值后的张量维度顺序调整回（batch_size,new_size*new_size,embedding_size）
            new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) #将额外的token与patch的token拼接
            checkpoint_model['pos_embed'] = new_pos_embed #将新的位置嵌入替换到预训练权重中


def convert_weights_to_fp16(model: nn.Module):
    """Convert applicable model parameters to fp16"""

    def _convert_weights_to_fp16(l):
        if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): #检查层l是否为一维卷积，二维卷积或全连接层
            l.weight.data = l.weight.data.half() #将权重数据转换为16位浮点数
            if l.bias is not None:
                l.bias.data = l.bias.data.half() #如果有偏置，将偏置项也转换为16位浮点数

#         if isinstance(l, (nn.MultiheadAttention, Attention)):
#             for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
#                 tensor = getattr(l, attr)
#                 if tensor is not None:
#                     tensor.data = tensor.data.half()

    model.apply(_convert_weights_to_fp16) #对模型中的每一层应用函数，将符合条件的层和权重和偏置转换为fp16格式

#用于创建并初始化一个特定配置的VisionTransformer模型
def create_eva_vit_g(
        url_or_filename="https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/eva_vit_g.pth",
        img_size=224, drop_path_rate=0.4, use_checkpoint=False, precision="fp16"):
    model = VisionTransformer(
        img_size=img_size,
        patch_size=14,
        use_mean_pooling=False,
        embed_dim=1408,
        depth=39,
        num_heads=1408//88,
        mlp_ratio=4.3637,
        qkv_bias=True,
        drop_path_rate=drop_path_rate,
        norm_layer=partial(nn.LayerNorm, eps=1e-6),
        use_checkpoint=use_checkpoint,
    ) #创建一个实例，配置参数包括图像大小，patch大学，嵌入维度，深度，注意力头数等
    if is_url(url_or_filename):
        cached_file = download_cached_file(
            url_or_filename, check_hash=False, progress=True
        ) #提供的权重文件路径如果是url，则下载文件到本地缓存
    elif os.path.isfile(url_or_filename):
        cached_file = url_or_filename #如果不是url，则检查是否为本地文件，如是则直接使用该路径
    else:
        raise RuntimeError("checkpoint url or path is invalid") #反之抛出错误
    state_dict = torch.load(cached_file, map_location="cpu") #加载缓存文件中的模型权重到cpu
    interpolate_pos_embed(model,state_dict) #调用函数对位置嵌入进行插值，以适应模型的patch数量

    incompatible_keys = model.load_state_dict(state_dict, strict=False)
#     print(incompatible_keys)

    if precision == "fp16":
        # model.to("cuda")
        convert_weights_to_fp16(model)
    return model
